<template>
  <div class="kiki-status-selector" data-kiki-status-selector="true">
    <div class="custom-select" :class="{ 'open': isOpen }">
      <div class="selected-option" @click="toggleDropdown">
        <span :style="getOptionStyle(internalStatus)">{{ getCurrentLabel() }}</span>
        <span class="arrow">▼</span>
      </div>
      <div class="options-container" v-if="isOpen">
        <div 
          class="option"
          :style="getOptionStyle('')"
          @click="selectOption('')"
        >
          筛选状态
        </div>
        <div 
          v-for="status in followStatusList" 
          :key="status.value"
          class="option"
          :style="getOptionStyle(status.value)"
          @click="selectOption(status.value)"
        >
          {{ status.label }}
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch, onMounted, onUnmounted } from 'vue';
import { getCurrentChatId } from '../utils/whatsappHandler';

interface StorageResult {
  [key: string]: any;
}

interface StatusItem {
  label: string;
  value: string;
}

interface StatusStyle {
  background: string;
  text: string;
}

// 状态颜色映射
const STATUS_COLORS: { [key: string]: StatusStyle } = {
  'new': {
    background: '#e3f2fd',
    text: '#1976d2'
  },
  'converted': {
    background: '#e8f5e9',
    text: '#2e7d32'
  },
  'focus_follow': {
    background: '#004d40',
    text: '#ffffff'
  },
  'potential': {
    background: '#fff3e0',
    text: '#e65100'
  },
  'high_potential': {
    background: '#ff9800',
    text: '#ffffff'
  },
  'public_customer': {
    background: '#f5f5f5',
    text: '#616161'
  },
  'bad_customer': {
    background: '#eeeeee',
    text: '#757575'
  },
  'ai_follow': {
    background: '#f3e5f5',
    text: '#7b1fa2'
  },
  'invalid': {
    background: '#fafafa',
    text: '#9e9e9e'
  },
  // 添加其他可能的状态
  'no_reply': {
    background: '#ffebee',
    text: '#c62828'
  },
  'replied': {
    background: '#e8f5e9',
    text: '#2e7d32'
  },
  'following': {
    background: '#e3f2fd',
    text: '#1976d2'
  },
  'closed': {
    background: '#f5f5f5',
    text: '#616161'
  }
};

// 默认状态颜色
const DEFAULT_STATUS_COLOR: StatusStyle = {
  background: '#f0f2f5',
  text: '#54656f'
};

// 扩展Window接口
declare global {
  interface Window {
    filterChatListDebounce?: Function;
    lastSelectedStatus?: string;
    updateGlobalInfo?: Function;
  }
}

export default defineComponent({
  name: 'StatusSelector',
  props: {
    followStatusList: {
      type: Array as PropType<StatusItem[]>,
      default: () => []
    },
    currentStatus: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const isOpen = ref(false);
    const lastChatId = ref('');
    const internalStatus = ref(window.lastSelectedStatus || '');

    // 获取当前对话的状态
    const getCurrentChatStatus = async () => {
      try {
        // 获取聊天标题映射
        const titleMapResult = await new Promise<StorageResult>(resolve => {
          chrome.storage.local.get(['kiki_chat_title_map'], resolve);
        });
        const titleMap = titleMapResult['kiki_chat_title_map'] || {};

        // 获取当前对话的标题
        const currentChatTitle = document.querySelector('#main span[dir="auto"]')?.textContent?.trim();
        if (currentChatTitle && titleMap[currentChatTitle]) {
          console.log('当前对话状态:', titleMap[currentChatTitle]);
          return titleMap[currentChatTitle];
        }
        return '';
      } catch (error) {
        console.error('获取当前对话状态出错:', error);
        return '';
      }
    };

    // 监听聊天ID变化
    watch(
      () => getCurrentChatId(),
      async (newChatId) => {
        if (newChatId && newChatId !== lastChatId.value) {
          lastChatId.value = newChatId;
          // 获取并设置当前对话的状态
          const currentStatus = await getCurrentChatStatus();
          if (currentStatus) {
            internalStatus.value = currentStatus;
            window.lastSelectedStatus = currentStatus;
            emit('status-change', currentStatus);
            if (window.filterChatListDebounce) {
              window.filterChatListDebounce(currentStatus);
            }
          }
        }
      },
      { immediate: true }
    );

    // 监听状态列表变化
    watch(() => props.followStatusList, (newList) => {
      console.log('状态列表更新:', newList);
      // 打印每个状态的值
      // newList.forEach(status => {
      //   console.log('状态值:', status.value, '标签:', status.label);
      // });
    }, { immediate: true });

    // 获取当前选中的标签文本
    const getCurrentLabel = () => {
      const currentValue = internalStatus.value;
      if (!currentValue) return '筛选状态';
      const status = props.followStatusList.find(s => s.value === currentValue);
      return status ? status.label : '筛选状态';
    };

    // 获取选项样式
    const getOptionStyle = (value: string) => {
      if (!value) {
        return {
          backgroundColor: DEFAULT_STATUS_COLOR.background,
          color: DEFAULT_STATUS_COLOR.text
        };
      }
      
      const colors = STATUS_COLORS[value] || DEFAULT_STATUS_COLOR;
      // console.log('获取样式，状态值:', value, '颜色:', colors);
      return {
        backgroundColor: colors.background,
        color: colors.text
      };
    };

    // 切换下拉菜单
    const toggleDropdown = () => {
      isOpen.value = !isOpen.value;
    };

    // 更新全局信息并显示提醒
    const updateGlobalInfo = async (status: string) => {
      try {
        // 获取当前对话的标题
        const currentChatTitle = document.querySelector('#main span[dir="auto"]')?.textContent?.trim();
        if (!currentChatTitle) {
          console.error('无法获取当前对话标题');
          return;
        }

        // 获取聊天标题映射
        const titleMapResult = await new Promise<StorageResult>(resolve => {
          chrome.storage.local.get(['kiki_chat_title_map'], resolve);
        });
        let titleMap = titleMapResult['kiki_chat_title_map'] || {};
        
        // 更新状态
        const oldStatus = titleMap[currentChatTitle] || '';
        titleMap[currentChatTitle] = status;
        
        // 保存更新后的映射
        await new Promise<void>(resolve => {
          chrome.storage.local.set({ 'kiki_chat_title_map': titleMap }, resolve);
        });
        
        // 显示提醒对话框
        if (oldStatus !== status) {
          const statusLabel = props.followStatusList.find(s => s.value === status)?.label || status;
          const message = status ? 
            `已将 "${currentChatTitle}" 的状态同步为 "${statusLabel}"` :
            `已清除 "${currentChatTitle}" 的状态`;
          
          showNotification(message);
        }
        
        console.log('更新全局信息成功:', currentChatTitle, status);
      } catch (error) {
        console.error('更新全局信息出错:', error);
      }
    };
    
    // 显示通知
    const showNotification = (message: string) => {
      // 创建通知元素
      const notification = document.createElement('div');
      notification.className = 'kiki-notification';
      notification.textContent = message;
      
      // 添加到页面
      document.body.appendChild(notification);
      
      // 动画显示
      setTimeout(() => {
        notification.classList.add('show');
      }, 10);
      
      // 3秒后移除
      setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
          document.body.removeChild(notification);
        }, 300);
      }, 3000);
    };

    // 选择选项
    const selectOption = (value: string) => {
      isOpen.value = false;
      if (value !== internalStatus.value) {
        internalStatus.value = value;
        window.lastSelectedStatus = value;
        emit('status-change', value);
        
        // 更新全局信息
        updateGlobalInfo(value);
        
        if (!window.filterChatListDebounce) {
          window.filterChatListDebounce = debounce(filterChatList, 300);
        }
        
        window.filterChatListDebounce(value);
      }
    };

    // 点击外部关闭下拉菜单
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.custom-select')) {
        isOpen.value = false;
      }
    };

    // 防抖函数
    const debounce = (fn: Function, delay: number) => {
      let timer: number | null = null;
      return function(...args: any[]) {
        if (timer) clearTimeout(timer);
        timer = window.setTimeout(() => {
          fn(...args);
          timer = null;
        }, delay);
      };
    };
    
    // 过滤聊天列表
    const filterChatList = async (selectedStatus: string) => {
      try {
        // 获取聊天标题映射
        const titleMapResult = await new Promise<StorageResult>(resolve => {
          chrome.storage.local.get(['kiki_chat_title_map'], resolve);
        });
        const titleMap = titleMapResult['kiki_chat_title_map'] || {};
        
        // 找到聊天列表容器
        const paneElement = document.querySelector('#pane-side') || 
                           document.querySelector('div[aria-label="对话列表"]');
        if (!paneElement) {
          console.error('无法找到聊天列表容器');
          return;
        }
        
        // 获取所有聊天项
        const chatRows = paneElement.querySelectorAll('[role="listitem"]');
        console.log('找到聊天行:', chatRows.length);
        
        // 找到虚拟滚动的容器
        const scrollContainer = paneElement.querySelector('div[style*="transform"]');
        if (!scrollContainer) {
          console.error('无法找到虚拟滚动容器');
          return;
        }
        
        if (selectedStatus === '') {
          // 显示所有对话
          chatRows.forEach(row => {
            const parentDiv = row.closest('div[style*="z-index"]') as HTMLElement | null;
            if (parentDiv) {
              // 重置原始位置
              const originalTransform = parentDiv.getAttribute('data-original-transform');
              if (originalTransform) {
                parentDiv.style.transform = originalTransform;
              }
              parentDiv.style.display = '';
            }
          });
        } else {
          let currentTop = 0; // 用于追踪当前位置
          const itemHeight = 72; // WhatsApp 聊天项的标准高度
          
          chatRows.forEach((row, index) => {
            const titleSpan = row.querySelector('span[title]');
            if (titleSpan) {
              const title = titleSpan.getAttribute('title')?.trim() || '';
              const chatStatus = titleMap[title];
              const parentDiv = row.closest('div[style*="z-index"]') as HTMLElement | null;
              
              if (parentDiv) {
                // 保存原始transform，以便恢复
                if (!parentDiv.hasAttribute('data-original-transform')) {
                  const originalTransform = parentDiv.style.transform;
                  parentDiv.setAttribute('data-original-transform', originalTransform);
                }
                
                if (chatStatus === selectedStatus) {
                  // 设置新的位置
                  parentDiv.style.transform = `translateY(${currentTop}px)`;
                  parentDiv.style.display = '';
                  currentTop += itemHeight;
                } else {
                  // 隐藏不匹配的项
                  parentDiv.style.display = 'none';
                }
              }
            }
          });
          
          // 更新容器高度
          const scrollContainerElement = scrollContainer as HTMLElement;
          scrollContainerElement.style.height = `${currentTop}px`;
        }
        
        // 触发滚动容器更新
        const forceRefresh = () => {
          if (paneElement) {
            // 记住滚动位置
            const paneHTMLElement = paneElement as HTMLElement;
            const scrollTop = paneHTMLElement.scrollTop;
            
            // 触发更新
            paneHTMLElement.style.display = 'none';
            void paneHTMLElement.offsetHeight;
            paneHTMLElement.style.display = '';
            
            // 恢复滚动位置
            requestAnimationFrame(() => {
              paneHTMLElement.scrollTop = scrollTop;
            });
          }
        };
        
        // 执行两次刷新，确保完全更新
        forceRefresh();
        setTimeout(forceRefresh, 100);
      } catch (error) {
        console.error('过滤聊天列表出错:', error);
      }
    };

    // 在组件挂载时恢复上次的状态
    onMounted(() => {
      document.addEventListener('click', handleClickOutside);
      if (window.lastSelectedStatus !== undefined) {
        selectOption(window.lastSelectedStatus);
      }
      
      // 设置全局更新函数
      window.updateGlobalInfo = updateGlobalInfo;
    });

    onUnmounted(() => {
      document.removeEventListener('click', handleClickOutside);
      // 清除全局函数
      window.updateGlobalInfo = undefined;
    });
    
    return {
      isOpen,
      getCurrentLabel,
      getOptionStyle,
      toggleDropdown,
      selectOption,
      filterChatList,
      internalStatus,
      updateGlobalInfo
    };
  }
});
</script>

<style>
/* 注意：这里移除了 scoped，因为我们需要样式应用到插入后的位置 */
.kiki-status-selector {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid rgba(134, 150, 160, 0.15);
  background-color: #fff;
  position: relative;
  z-index: 1000;
}

.custom-select {
  width: 100%;
  position: relative;
}

.selected-option {
  width: 100%;
  padding: 8px 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  background-color: white;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 36px;
  box-sizing: border-box;
}

.selected-option:hover {
  border-color: #00a884;
}

.arrow {
  font-size: 12px;
  color: #54656f;
  transition: transform 0.2s;
  margin-left: 8px;
}

.custom-select.open .arrow {
  transform: rotate(180deg);
}

.options-container {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 4px;
  background: white;
  border-radius: 8px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  z-index: 1001;
}

.option {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 14px;
  line-height: 1.4;
}

.option:hover {
  filter: brightness(0.95);
}

/* 自定义滚动条样式 */
.options-container::-webkit-scrollbar {
  width: 6px;
}

.options-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.options-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.options-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 确保在WhatsApp中正确显示 */
.kiki-status-selector:not(:empty) {
  display: flex !important;
  visibility: visible !important;
  opacity: 1 !important;
}

/* 通知样式 */
.kiki-notification {
  position: fixed;
  top: 20px;
  right: 50%;
  background-color: rgba(0, 168, 132, 0.55);
  color: white;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10000;
  opacity: 0;
  transform: translateY(-20px);
  transition: opacity 0.3s, transform 0.3s;
  max-width: 300px;
  font-size: 14px;
  line-height: 1.4;
}

.kiki-notification.show {
  opacity: 1;
  transform: translateY(0);
}
</style> 